package com.xxx.dict.controller;

import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;

import com.xxx.dict.domain.DictItem;
import com.xxx.dict.query.DictItemQuery;

import com.xxx.dict.service.IDictItemService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author BoWei Wang
 * @date 2025/8/5
 */

@RestController
@RequestMapping("/dict_item")
@Api(tags = "字典明细 接口类")
public class DictItemController {
    @Autowired
    private IDictItemService dictItemService;

    @GetMapping
    @ApiOperation("查询所有字典明细 ")
    public R<List<DictItem>> findAll() {
        return R.ok(dictItemService.findAll());
    }

    @GetMapping("/{id}")
    @ApiOperation("查询单个字典明细 ")
    public R<DictItem> findOne(@PathVariable Long id) {
        return R.ok(dictItemService.findOne(id));
    }

    @PostMapping
    @ApiOperation("分页条件查询字典明细 ")
    public PageInfo<DictItem> queryPage(@RequestBody DictItemQuery dictItemQuery) {
        List<DictItem> dictItems = dictItemService.queryPage(dictItemQuery);
        return new PageInfo<DictItem>(dictItems);
    }

    @PostMapping("/add")
    @ApiOperation("添加字典明细 ")
    public R<Void> addDictItem(@RequestBody DictItem dictItem) {
        dictItemService.addDictItem(dictItem);
        return R.ok();
    }

    @PutMapping
    @ApiOperation("新增修改字典明细 ")
    public R<Void> addOrUpdateDictItem(@RequestBody DictItem dictItem) {
        try {
            if (dictItem.getId() == null) {
                dictItemService.addDictItem(dictItem);
            } else {
                dictItemService.updateDictItem(dictItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("字典明细 名已存在!");
        }
        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除字典明细 ")
    public R<Void> deleteDictItem(@PathVariable Long id) {
        try {
            dictItemService.deleteDictItem(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @PatchMapping
    @ApiOperation("批量删除字典明细 ")
    public R<Void> batchDeleteDictItems(@RequestBody Long[] ids) {
        try {
            dictItemService.batchDeleteDictItems(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @GetMapping("/getByDictId/{dictId}")
    @ApiOperation("通过字典查询字典明细")
    public R<List<DictItem>> getByDictId(@PathVariable Long dictId) {
        return R.ok(dictItemService.getByDictId(dictId));
    }

}
